package com.journaldev.spring.dao;

import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.transaction.annotation.Transactional;

import com.journaldev.spring.model.Patient;

@Transactional
public class PatientDAOImpl implements PatientDAO {
	
	private static final Logger logger = LoggerFactory.getLogger(DistrictDAOImpl.class);

	private SessionFactory sessionFactory;
	
	public void setSessionFactory(SessionFactory sf){
		this.sessionFactory = sf;
	}

	@Override
	public void addPatient(Patient p) {
		// TODO Auto-generated method stub
		Session session = this.sessionFactory.getCurrentSession();
		session.persist(p);
		logger.info("Patient saved successfully, Patient Details="+p);
	}

	@Override
	public void updatePatient(Patient p) {
		// TODO Auto-generated method stub
		Session session = this.sessionFactory.getCurrentSession();
		session.update(p);
		logger.info("Patient updated successfully, Patient Details="+p);
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Patient> listPatient() {
		// TODO Auto-generated method stub
		Session session = this.sessionFactory.getCurrentSession();
		List<Patient> patientList = session.createQuery("from Patient").list();
		for(Patient p : patientList){
			logger.info("Patient List::"+p);
		}
		return patientList;
	}

	@Override
	public Patient getPatientById(int id) {
		// TODO Auto-generated method stub
		Session session = this.sessionFactory.getCurrentSession();		
		Patient p = (Patient) session.get(Patient.class, new Integer(id));
		logger.info("Patient loaded successfully, Patient details="+p);
		return p;
	}

	@Override
	public void removePatient(int id) {
		// TODO Auto-generated method stub
		Session session = this.sessionFactory.getCurrentSession();
		Patient p = (Patient) session.get(Patient.class, new Integer(id));
		if(null != p){
			session.delete(p);
		}
		logger.info("Patient deleted successfully, Patient details="+p);
	}

}
